<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<html>
<body>
</body>
<script>

function updateCourse(action, elem){
	var inputs = elem.parentNode.getElementsByTagName('input');
	
	var xhr = new XMLHttpRequest(),
		params = {}, params2 = [];
	xhr.open('POST', "http://localhost:8080/MyProj/servlet/CourseManage", true);
	params['action'] = action;
	params['courseID'] = inputs[0].value;
	params['courseName'] = inputs[1].value;
	params['description'] = inputs[2].value;
	params['teacher'] = inputs[3].value;
	
	for (var i in params){
		params2.push(i + '=' + encodeURIComponent(params[i]));
	}
	
	xhr.onreadystatechange = function(){
		if (xhr.readyState==4 && xhr.status==200) {
			console.log(xhr.responseText);
			loadData();
		}
	};
	xhr.send(params2.join("&"));
}

function loadData(){
	var xhr = new XMLHttpRequest();
	
	xhr.open("GET", "http://localhost:8080/MyProj/servlet/CourseQuery", false);
	
	xhr.send("null");
	
	eval("var data = " + xhr.responseText);
	
	var tableHTML = "<table>";
	tableHTML += '<colgroup><col></col><col></col><col></col><col></col></colgroup>';
	tableHTML += '<tr><th>课程编号</th><th>课程名称</th><th>描述</th><th>任课老师</th><th></th></tr>';
	for (var i = 0; i < data.length; i++ ){
		tableHTML += '<tr>';
		tableHTML += '<td><input value="' + data.courseID + '" name="courseID"></td>';
		tableHTML += '<td><input value="' + data.name + '" name="name"></td>';
		tableHTML += '<td><input value="' + data.description + '" name="description"></td>';
		tableHTML += '<td><input value="' + data.teacher + '" name="teacher"></td>';
		tableHTML += '<td><button onclick="updateCourse(\"update\", this);">' + 更新 + '</button>' 
					   + '<button onclick="updateCourse(\"delete\", this);">' + 删除 + '</button></td>';
		tableHTML += '</tr>';
	}
	tableHTML += '<tr>';
	tableHTML += '<td><input name="courseID"></td>';
	tableHTML += '<td><input name="name"></td>';
	tableHTML += '<td><input name="description"></td>';
	tableHTML += '<td><input name="teacher"></td>';
	tableHTML += '<td><button onclick="updateCourse(\"add\", this);">' + 新增 + '</button></td>';
	tableHTML += '</tr>';
	tableHTML += '</table>';
	
	var div = document.getElementById('courseList');
	if (!div){
		div = document.createElement('div');
		div.id = 'courseList';
		document.body.appendChild(div);
	}
	div.innerHTML = tableHTML;
}
</script>
</html>